package com.xframe.common.core.api;

import cn.hutool.core.util.IdUtil;
import com.xframe.common.core.constant.ErrorConstant;
import com.xframe.common.core.dto.*;
import com.xframe.common.core.exception.BusinessException;
import com.xframe.common.core.export.FactoryByExportFormat;
import com.xframe.common.core.export.IBuilderFileTo;
import com.xframe.domain.ModelRepositoryFactory;
import com.xframe.common.core.service.CommandProcService;
import com.xframe.common.core.service.IProcCommandService;
import com.xframe.domain.CommandBodyContainer;
import com.xframe.domain.CommandModel;
import com.xframe.domain.WareHouseBaseData;
import com.xframe.domain.repository.SysBaseRepository;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.domain.sys.SysModel;
import com.xframe.domain.sys.SysModelMany;
import com.xframe.xdal.core.domain.SysBaseEntity;
import com.xframe.xdal.core.domain.XDynamicModel;
import com.xframe.xdal.core.model.BuildModelHelp;
import com.xframe.xdal.core.model.ConditionValue;
import com.xframe.xdal.core.model.DbSort;
import com.xframe.xdal.core.model.FindOptions;
import com.xframe.xdal.core.model.page.IPagerModel;
import com.xframe.xdal.core.serialize.IJSONSer;
import com.xframe.xdal.core.serialize.JsonConfig;
import com.xframe.xdal.core.serialize.JsonConfigContainer;
import com.xframe.xdal.core.serialize.JsonSerFactory;
import com.xframe.xdal.core.serialize.lang.LanguageEnvironmentContext;
import com.xframe.xdal.core.util.CollectionUtil;
import com.xframe.xdal.core.util.StringUtil;
import com.xframe.xdal.core.util.UUIDCreateUtil;
import com.xframe.xdal.core.util.redis.RedisAccess;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import com.xframe.common.core.service.ExportAsyncService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 功能描述:带有通用的查询、导出、执行命令的Controller
 *
 * @author xufeng
 * @version 1.0
 * 2022-09-26
 */
@Log4j2
public class GenericityController extends BaseController{
    @Lazy
    @Autowired
    protected CommandProcService procFactory;

    @Lazy
    @Autowired
    protected ExportAsyncService exportAsyncService;

    @Value("${down.basePath}")
    private String downBasePath;

    @Value("${image.basePath}")
    private String imageBasePath;

    @Value("${image.dir}")
    private String imageDir;


    public static final Integer EXPORT_MAX_COUNT = 1000;

    public static final Integer QUERY_MAX_COUNT = 500;

    public static final Integer SELECT_QUERY_MAX_COUNT = 100;
    /**
     * 执行命令  
     * @param infos
     * @return
     */
    @PostMapping({ "/execute" })
    @ResponseBody
    public ResultDTO<Object> execute(@RequestBody CommandModel infos) {
        try {
            if(StringUtil.isEmpty(infos.getModelCode())){
                if(StringUtil.isNotEmpty(infos.getClassName())){
                    infos.setModelCode(infos.getClassName());
                }
            }
            IProcCommandService cmd = procFactory.Create(infos);
            IUserCredentials userCredentials = checkUserToken(cmd.needCheckToken());
            CommandBodyContainer.addCommandModel(infos);
            Object obj = cmd.ProcCommand(infos,userCredentials);
            return new ResultDTO<>().setResult(obj);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(),ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }finally {
            CommandBodyContainer.remove();
        }
    }

    /**
     * 查询列表
     *
     * @param queryDTO 查询条件
     * @return
     */
    @PostMapping({"/queryModelListByPage"})
    @ResponseBody
    public ResultDTO<Object> queryListByPage(@RequestBody QueryDTO queryDTO) {
        try {
            IUserCredentials userCredentials = checkUserToken();

            FindOptions findOptions = FindOptions.defFindAllOptionsByPage();

            findOptions.setPageIndex(queryDTO.getPageIndex());
            findOptions.setPageSize(queryDTO.getPageSize());

            findOptions.setRecordCountFlag(queryDTO.getRecordCountFlag());
            if (queryDTO.getConditions() != null && queryDTO.getConditions().size() > 0) {
                for (int i = 0; i < queryDTO.getConditions().size(); i++) {
                    findOptions.getConditionValueCollection().add(queryDTO.getConditions().get(i).toConditionValue());
                }
            }

            if (!StringUtil.isEmpty(queryDTO.getSortName())) {
                if (StringUtil.isEmpty(queryDTO.getSortDir())) {
                    queryDTO.setSortDir("ASC");
                }
                findOptions.getDbSortCollection().add(new DbSort(queryDTO.getSortName(), DbSort.SortDir.valueOf(queryDTO.getSortDir().toUpperCase())));
            }

            if(queryDTO.getRefList() != null && queryDTO.getRefList().size() > 0) {
                findOptions.setRefList(queryDTO.getRefList());
            }

            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }

            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            SysBaseRepository repository = ModelRepositoryFactory.builder(sysModel);
            Class<?> dataType = queryDTO.getDataType();
            if (dataType == null) {
                dataType = sysModel.getModelDataType();
            }
            IPagerModel<Object> collection = repository.queryModleByPage(dataType,sysModel,findOptions);
            IJSONSer jsonSer = JsonSerFactory.create(sysModel);

            Object dic = jsonSer.toJsonObj(collection.getDataList(),sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            collection.setDataList(dic);
            return new ResultDTO<>().setResult(collection);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }




    /**
     * 查询列表 
     *
     * @param queryDTO 查询条件
     * @return
     */
    @PostMapping({"/queryModelList"})
    @ResponseBody
    public ResultDTO<Object> queryList(@RequestBody QueryDTO queryDTO) {
        try {
            IUserCredentials userCredentials = checkUserToken();

            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            Class<?> dataType = queryDTO.getDataType();
            if (dataType == null) {
                dataType = sysModel.getModelDataType();
            }
            FindOptions findOptions = FindOptions.defFindAllOptions();
//            findOptions.setPageIndex(1);
//            findOptions.setPageSize(QUERY_MAX_COUNT);
            if (queryDTO.getConditions() != null && queryDTO.getConditions().size() > 0) {
                for (ConditionValueDto conditionValueDto : queryDTO.getConditions()) {
                    if (StringUtil.isNotEmptyObject(conditionValueDto.getVal())){
                        findOptions.addConditionValue(conditionValueDto.toConditionValue());
                    }
                }
            }
            if (StringUtil.isNotEmpty(queryDTO.getSortName())) {
                if (StringUtil.isEmpty(queryDTO.getSortDir())) {
                    queryDTO.setSortDir("ASC");
                }
                findOptions.addDbSort(new DbSort(queryDTO.getSortName(), DbSort.SortDir.valueOf(queryDTO.getSortDir().toUpperCase())));
            }
            if(CollectionUtil.isNotEmpty(queryDTO.getRefList())) {
                findOptions.setRefList(queryDTO.getRefList());
            };
            SysBaseRepository repository = ModelRepositoryFactory.builder(sysModel);
            IJSONSer jsonSer = JsonSerFactory.create(sysModel);
            Object collection = repository.queryModle(dataType,sysModel,findOptions);
            Object dic = jsonSer.toJsonObj(collection,sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            //IPagerModel<Object> collection = repository.queryModleByPage(dataType,sysModel,findOptions);
            //Object dic = jsonSer.toJsonObj(collection.getDataList(),sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            return new ResultDTO<>().setResult(dic);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }


    /**
     * 文件导出
     *
     * @param queryDTO 查询条件
     * @return
     */
    @PostMapping({"/export"})
    @ResponseBody
    public ResultDTO<Object> export(@RequestBody QueryExportDTO queryDTO){
        try {
            IUserCredentials userCredentials = checkUserToken();
            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            Class<?> dataType = queryDTO.getDataType();
            if (dataType == null) {
                dataType = sysModel.getModelDataType();
            }
            FindOptions findOptions = FindOptions.defFindAllOptions();
            findOptions.setPageIndex(1);
            findOptions.setPageSize(EXPORT_MAX_COUNT);
            if (queryDTO.getConditions() != null && queryDTO.getConditions().size() > 0) {
                for (ConditionValueDto conditionValueDto : queryDTO.getConditions()) {
                    if (StringUtil.isNotEmptyObject(conditionValueDto.getVal())){
                        findOptions.addConditionValue(conditionValueDto.toConditionValue());
                    }
                }
            }
            if (StringUtil.isNotEmpty(queryDTO.getSortName())) {
                if (StringUtil.isEmpty(queryDTO.getSortDir())) {
                    queryDTO.setSortDir("ASC");
                }
                findOptions.addDbSort(new DbSort(queryDTO.getSortName(), DbSort.SortDir.valueOf(queryDTO.getSortDir().toUpperCase())));
            }
            if(CollectionUtil.isNotEmpty(queryDTO.getRefList())) {
                findOptions.setRefList(queryDTO.getRefList());
            };

            SysBaseRepository repository = ModelRepositoryFactory.builder(sysModel);


            IJSONSer jsonSer = JsonSerFactory.create(sysModel);
            //Object collection = repository.queryModle(dataType,sysModel,findOptions);
            IPagerModel<Object> collection = repository.queryModleByPage(dataType,sysModel,findOptions);
            JsonConfig jsonConfig = JsonConfigContainer.getConfigContainer().getJsonConfig(userCredentials.getLanguage(),
                    queryDTO.getVer(),sysModel.getModelCode(),queryDTO.getQueryKey());
            Object dic = jsonSer.toJsonObj(collection.getDataList(),sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            // 生成文件
            //String contextPath = request.getServletContext().getContextPath();
            File dir = new File(StringUtil.EMPTY);
            String rootPath = dir.getCanonicalPath() + File.separator;
            log.info(rootPath);
            IBuilderFileTo builderFileTo = FactoryByExportFormat.create(queryDTO.getExportFormat());
            DownFileDto downFileDto = builderFileTo.builderFile(jsonConfig.getJsonModelList(),(Collection)dic,
                    rootPath + this.downBasePath + File.separator,userCredentials.getLanguage(),queryDTO.getModelCode()
            ,queryDTO.getVer(),queryDTO.getQueryKey());
            // 根据类型 来决定导出工厂
            return new ResultDTO<>().setResult(downFileDto);

        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }


    /**
     * 文件导出(异步)
     *
     * @param queryDTO 查询条件
     * @return
     */
    @PostMapping({"/asyncExport"})
    @ResponseBody
    public ResultDTO<Object> asyncExport(@RequestBody QueryExportDTO queryDTO){
        try {
            IUserCredentials userCredentials = checkUserToken();
            Class<?> dataType = queryDTO.getDataType();
            if (dataType == null) {
                dataType = XDynamicModel.class;
            }
            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            FindOptions findOptions = FindOptions.defFindAllOptions();
            findOptions.setPageIndex(1);
            findOptions.setPageSize(EXPORT_MAX_COUNT);
            if (queryDTO.getConditions() != null && queryDTO.getConditions().size() > 0) {
                for (ConditionValueDto conditionValueDto : queryDTO.getConditions()) {
                    if (StringUtil.isNotEmptyObject(conditionValueDto.getVal())){
                        findOptions.addConditionValue(conditionValueDto.toConditionValue());
                    }
                }
            }
            if (StringUtil.isNotEmpty(queryDTO.getSortName())) {
                if (StringUtil.isEmpty(queryDTO.getSortDir())) {
                    queryDTO.setSortDir("ASC");
                }
                findOptions.addDbSort(new DbSort(queryDTO.getSortName(), DbSort.SortDir.valueOf(queryDTO.getSortDir().toUpperCase())));
            }
            if(CollectionUtil.isNotEmpty(queryDTO.getRefList())) {
                findOptions.setRefList(queryDTO.getRefList());
            };

            String asyncId = IdUtil.fastSimpleUUID();
            AsyncReportDTO asyncReportDTO = new AsyncReportDTO();
            asyncReportDTO.setAsyncId(asyncId);
            asyncReportDTO.setRate(0);
            asyncReportDTO.setStatus("init");
            RedisAccess.getSetCmd().setObject(asyncId, asyncReportDTO, 60 * 10);
            //log.info(Thread.currentThread().getName() + " in export, before export.");
            exportAsyncService.exportToFile(asyncId,queryDTO,findOptions,dataType,sysModel,this.downBasePath,userCredentials);
            //log.info(Thread.currentThread().getName() + " in export, after export.");
            return new ResultDTO<>().setResult(asyncReportDTO);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }


    @PostMapping({"/asyncReport"})
    @ResponseBody
    public ResultDTO<Object> asyncReport(@RequestBody QueryAsyncDTO dto){

        try {
            AsyncReportDTO asyncReportDTO = RedisAccess.getGetCmd().getObject(dto.getAsyncId(), AsyncReportDTO.class);
            if(asyncReportDTO == null){
                throw new BusinessException(ErrorCode.ASYNC_ID_ERROR, ErrorConstant.INTERNAL_SERVER_ERROR_MSG);
            }
            return new ResultDTO<>().setResult(asyncReportDTO);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }


    @PostMapping({"/downloadFile"})
    @ResponseBody
    public void downloadFile(@RequestBody DownFileDto dto,
                                                 HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        File dir = new File("");
        String rootPath = dir.getCanonicalPath() + File.separator;
        log.info(rootPath);
        String downPath = rootPath + this.downBasePath + File.separator;
        File file = new File(downPath + dto.getFileName() + "." + dto.getFileFormat());

        String modelName = LanguageEnvironmentContext.getInstance().getModelName(dto.getLanguage(), dto.getModelCode());
        if(StringUtil.isEmpty(modelName)){
            SysModel sysModel = SysModel.getInstance(dto.getModelCode());
            if(sysModel != null){
                modelName = sysModel.getModelName();
            }else {
                modelName = dto.getFileName();
            }
        }
        String showName = modelName + "." + dto.getFileFormat();

        String encodedFileName = URLEncoder.encode(showName, "UTF-8");
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
        response.addHeader("Content-Length",String.valueOf(file.length()));
        response.setContentType("application/octet-stream");



        // 读取文件并将其写入响应输出流
        try (InputStream in = new FileInputStream(file.getAbsolutePath());
             OutputStream out = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

    }




    /**
     * 查询单条数据
     *
     * @param queryDTO 查询条件
     * @return
     */
    @PostMapping({"/queryById"})
    @ResponseBody
    public ResultDTO<Object> queryById(@RequestBody QueryByKeyDTO queryDTO){
        try {
            IUserCredentials userCredentials = checkUserToken();
            Class<?> dataType = queryDTO.getDataType();
            if (dataType == null) {
                dataType = XDynamicModel.class;
            }
            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            FindOptions findOptions = FindOptions.defFindAllOptionsByPage();
            findOptions.getRefList().add(SysBaseEntity.FULL_DATA);
            if(CollectionUtil.isNotEmpty(queryDTO.getRefList())) {
                findOptions.setRefList(queryDTO.getRefList());
            }
            SysBaseRepository repository = ModelRepositoryFactory.builder(sysModel);

            Object model = repository.findByPK(dataType,queryDTO.getId(), sysModel,findOptions.getRefList().toArray(new String[0]));
            IJSONSer jsonSer = JsonSerFactory.create(sysModel);
            Object dic = jsonSer.toJsonObj(model,sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            return new ResultDTO<>().setResult(dic);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }

    /**
     * 查询单条数据
     *
     * @param queryDTO 查询条件
     * @return
     */
    @PostMapping({"/queryModelByView"})
    @ResponseBody
    public ResultDTO<Object> queryModelByView(@RequestBody QueryByKeyDTO queryDTO){
        try {
            IUserCredentials userCredentials = checkUserToken();
            Class<?> dataType = queryDTO.getDataType();
            if (dataType == null) {
                dataType = XDynamicModel.class;
            }
            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            FindOptions findOptions = FindOptions.defFindAllOptionsByPage();
            findOptions.getRefList().add(SysBaseEntity.BELONG_FULL_DATA);
            if(CollectionUtil.isNotEmpty(queryDTO.getRefList())) {
                findOptions.setRefList(queryDTO.getRefList());
            }
            SysBaseRepository repository = ModelRepositoryFactory.builder(sysModel);

            Object model = repository.findByPK(dataType,queryDTO.getId(), sysModel,findOptions.getRefList().toArray(new String[0]));
            IJSONSer jsonSer = JsonSerFactory.create(sysModel);

            Map<String,Object> reMap = new HashMap<>();

            Object dic = jsonSer.toJsonObj(model,sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            reMap.put("model",dic);
            if(sysModel.getModelManyList() != null && sysModel.getModelManyList().size() > 0){
                List<HashMap<String,Object>> manyList = new ArrayList<>();
                for(SysModelMany sysModelMany : sysModel.getModelManyList()){
                    HashMap<String,Object> info = new HashMap<>();
                    info.put("modelCode",sysModelMany.getTarModelCode());
                    info.put("name",sysModelMany.getAsName());
                    info.put("keyName",sysModelMany.getFKey());
                    info.put("tarKey",sysModelMany.getTarKey());
                    manyList.add(info);
                }
                reMap.put("listInfo",manyList);
            }else {
                reMap.put("listInfo",null);
            }
            return new ResultDTO<>().setResult(reMap);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }


    /**
     * 根据查询条件 获得下拉选择框的数据或者弹出网格选择框的数据
     *
     * @param queryDTO 查询条件  CredentialsContainer
     * @return JSON
     */
    @PostMapping({"/selectList"})
    @ResponseBody
    public ResultDTO<Object> selectList(@RequestBody SelectQueryDto queryDTO){
        try {
            IUserCredentials userCredentials = checkUserToken();
            if(StringUtil.isEmpty(queryDTO.getModelCode())){
                throw new BusinessException(ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(queryDTO.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, queryDTO.getModelCode()));
            }
            Class<?> dataType = XDynamicModel.class;


            FindOptions findOptions = FindOptions.defFindAllOptions();
//            findOptions.setPageIndex(1);
//            findOptions.setPageSize(SELECT_QUERY_MAX_COUNT);
            //BuildModel.buildConditionValueCollection(queryDTO.getFilter());
            findOptions.setConditionValueCollection(BuildModelHelp.buildConditionValueCollection(queryDTO.getFilter()));
            findOptions.setDbSortCollection(BuildModelHelp.buildDbSortCollection(queryDTO.getSorts()));

            if(WareHouseBaseData.class.isAssignableFrom(sysModel.getModelDataType())){
                findOptions.addConditionValue(new ConditionValue(WareHouseBaseData.ATT_NAME,userCredentials.getOrgId()));
            }

            SysBaseRepository repository = ModelRepositoryFactory.builder(sysModel);
            IJSONSer jsonSer = JsonSerFactory.create(sysModel);

            Object collection = repository.queryModle(dataType,sysModel,findOptions);
            Object dic = jsonSer.toJsonObj(collection,sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());


//            IPagerModel<Object> collection = repository.queryModleByPage(dataType,sysModel,findOptions);
//            Object dic = jsonSer.toJsonObj(collection.getDataList(),sysModel,userCredentials.getLanguage(),queryDTO.getQueryKey(),queryDTO.getVer());
            return new ResultDTO<>().setResult(dic);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }


    /**
     * 文件上传
     * @return
     */
    @ApiOperation(value = "上传文件")
    @PostMapping("/upload/annex")
    public ResultDTO<Object> importFile(
            @RequestParam(value = "fileTypeKey") String fileTypeKey,
            @RequestParam(value = "sysCode") String sysCode,
            @RequestPart("file") MultipartFile file
            ) {
        try {
            IUserCredentials userCredentials = checkUserToken();
            String rootPath = "";
            String url = "";
            if(StringUtil.isEmpty(this.imageBasePath)){
                File dir = new File(StringUtil.EMPTY);
                rootPath = dir.getCanonicalPath() + File.separator + this.imageDir
                        + File.separator + sysCode + File.separator + fileTypeKey + File.separator;

                url =  "/" + this.imageDir
                        + "/" + sysCode + "/" + fileTypeKey + "/";
            }else {
                rootPath = this.imageBasePath + this.imageDir
                        + File.separator + sysCode + File.separator + fileTypeKey + File.separator;

                url = "/" + this.imageDir
                        + "/" + sysCode + "/" + fileTypeKey + "/";
            }

            File rootPathDir = new File(rootPath);
            if (!rootPathDir.exists()) {
                rootPathDir.mkdirs();
            }
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;
            url = url + fileName;
            String fileFullPath = rootPath + fileName;

            

            log.info(fileFullPath);
            file.transferTo(new File(fileFullPath));

            return new ResultDTO<>().setResult(url);
        } catch (BusinessException ex) {
            return new ResultDTO<>().error(ex.getCode(), ex.getMessage());
        } catch (Exception ex) {
            return new ResultDTO<>().error(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage());
        }

    }





}
